package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;

/**
 * @author： pang-yun
 * @date： 2021-11-29 15:13
 * 功能目的 ：用于 filter
 */

public class AdminFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(filterConfig.getFilterName());
        System.out.println(filterConfig.getServletContext().getAttributeNames());
        System.out.println(filterConfig.getInitParameter("name"));
    }

    /**
     * 专门用于拦截请求
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();
        Object user = Optional.ofNullable(session.getAttribute("user")).orElse("");
        if (user.equals("pang")) {
            // 让程序继续向下访问用户的目标资源
           filterChain.doFilter(servletRequest,servletResponse);
        }
        return;
    }

    @Override
    public void destroy() {

    }

}
